{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 百度AI--菜品识别"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### （1）首先需要通过API Key和Secret Key获取access_token"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>0</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>refresh_token</th>\n",
       "      <td>25.6edfee697aa4d6c8a872d2ce09cd13b7.315360000....</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>expires_in</th>\n",
       "      <td>2592000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>session_key</th>\n",
       "      <td>9mzdDxM9gnwJDlAiWeRxiTIVAGypH5mgn1kWa8W0h1zvyt...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>access_token</th>\n",
       "      <td>24.4738cd37e39c4dd2f8e81e0b4f8c50c7.2592000.15...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>scope</th>\n",
       "      <td>brain_asr_async brain_speech_realtime vis-face...</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>session_secret</th>\n",
       "      <td>67dc9fa06f550d6441842bf168cc127a</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                                                0\n",
       "refresh_token   25.6edfee697aa4d6c8a872d2ce09cd13b7.315360000....\n",
       "expires_in                                                2592000\n",
       "session_key     9mzdDxM9gnwJDlAiWeRxiTIVAGypH5mgn1kWa8W0h1zvyt...\n",
       "access_token    24.4738cd37e39c4dd2f8e81e0b4f8c50c7.2592000.15...\n",
       "scope           brain_asr_async brain_speech_realtime vis-face...\n",
       "session_secret                   67dc9fa06f550d6441842bf168cc127a"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "'24.4738cd37e39c4dd2f8e81e0b4f8c50c7.2592000.1597592080.282335-15803531'"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# A-1 获取access_token等参数信息\n",
    "# encoding:utf-8\n",
    "# client_id 为官网获取的AK， client_secret 为官网获取的SK\n",
    "host = 'https://aip.baidubce.com/oauth/2.0/token?'\n",
    "params = {\n",
    "    \"grant_type\":\"client_credentials\",\n",
    "    \"client_id\":\"kVcnfD9iW2XVZSMaLMrtLYIz\",\n",
    "    \"client_secret\":\"O9o1O213UgG5LFn0bDGNtoRN3VWl2du6\"\n",
    "}\n",
    "response = requests.get(host,params=params)\n",
    "display(pd.json_normalize(response.json()).T)\n",
    "\n",
    "access_token=response.json()[\"access_token\"]\n",
    "access_token"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### （2 ）接着对菜品进行识别"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'error_code': 6, 'error_msg': 'No permission to access data'}\n"
     ]
    }
   ],
   "source": [
    "# encoding:utf-8\n",
    "\n",
    "import requests\n",
    "import base64\n",
    "\n",
    "'''\n",
    "菜品识别\n",
    "'''\n",
    "\n",
    "request_url = \"https://aip.baidubce.com/rest/2.0/image-classify/v2/dish\"\n",
    "# 二进制方式打开图片文件\n",
    "f = open('D:/用户目录/下载/API/1.png', 'rb')\n",
    "img = base64.b64encode(f.read())\n",
    "\n",
    "params = {\"image\":img,\"top_num\":5}\n",
    "access_token = '24.252ab7e9d8bcb429492334abcb52f52c.2592000.1597591470.282335-15803531'\n",
    "request_url = request_url + \"?access_token=\" + access_token\n",
    "headers = {'content-type': 'application/x-www-form-urlencoded'}\n",
    "response = requests.post(request_url, data=params, headers=headers)\n",
    "if response:\n",
    "    print (response.json())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 有道智云AI开放平台--图片翻译（自然语言翻译）"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "b'{\"orientation\":\"Up\",\"RequestId\":\"a40438bc-8356-4b87-a0eb-9ec4b1bc0737\",\"image_size\":[1050,1680],\"lanFrom\":\"zh-CHS\",\"textAngle\":\"0.0\",\"errorCode\":\"0\",\"lanTo\":\"en\",\"exif\":\"Up\",\"resRegions\":[{\"boundingBox\":\"928,324,163,154\",\"linesCount\":1,\"lineheight\":44,\"context\":\"Y44\",\"tranContent\":\"Y44\",\"dir\":\"h\",\"lang\":\"en\"},{\"boundingBox\":\"430,827,194,210\",\"linesCount\":1,\"lineheight\":59,\"context\":\"itt\",\"tranContent\":\"itt\",\"dir\":\"v\",\"lang\":\"zh-CHS\"}]}'\n"
     ]
    }
   ],
   "source": [
    "import sys\n",
    "import uuid\n",
    "import requests\n",
    "import base64\n",
    "import hashlib\n",
    "\n",
    "from imp import reload\n",
    "\n",
    "reload(sys)\n",
    "\n",
    "YOUDAO_URL = 'https://openapi.youdao.com/ocrtransapi'\n",
    "APP_KEY = '303f98295cd51a1d'\n",
    "APP_SECRET = 'CmEtuTIVOZVEvwqBPOtnLxbMkK7IYMPm'\n",
    "\n",
    "\n",
    "def truncate(q):\n",
    "    if q is None:\n",
    "        return None\n",
    "    size = len(q)\n",
    "    return q if size <= 20 else q[0:10] + str(size) + q[size - 10:size]\n",
    "\n",
    "\n",
    "def encrypt(signStr):\n",
    "    hash_algorithm = hashlib.md5()\n",
    "    hash_algorithm.update(signStr.encode('utf-8'))\n",
    "    return hash_algorithm.hexdigest()\n",
    "\n",
    "\n",
    "def do_request(data):\n",
    "    headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n",
    "    return requests.post(YOUDAO_URL, data=data, headers=headers)\n",
    "\n",
    "\n",
    "def connect():\n",
    "    f = open(r'D:/用户目录/下载/API/1.png', 'rb')  # 二进制方式打开图文件(添加自己的图片具体路径)\n",
    "    q = base64.b64encode(f.read()).decode('utf-8')  # 读取文件内容，转换为base64编码\n",
    "    f.close()\n",
    "\n",
    "    data = {}\n",
    "    data['from'] = 'zh-CHS'\n",
    "    data['to'] = 'en'\n",
    "    data['type'] = '1'\n",
    "    data['q'] = q\n",
    "    salt = str(uuid.uuid1())\n",
    "    signStr = APP_KEY + q + salt + APP_SECRET\n",
    "    sign = encrypt(signStr)\n",
    "    data['appKey'] = APP_KEY\n",
    "    data['salt'] = salt\n",
    "    data['sign'] = sign\n",
    "\n",
    "    response = do_request(data)\n",
    "    print(response.content)\n",
    "\n",
    "\n",
    "if __name__ == '__main__':\n",
    "    connect()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
